package net.jueb.protobufs.server;

import java.util.HashMap;
import com.google.protobuf.MessageLite;
import net.jueb.protobufs.codec.ProtobufsDecoder;
import net.jueb.protobufs.codec.ProtobufsDispatcherDecoder;
import net.jueb.protobufs.codec.ProtobufsEncoder;
import net.jueb.protobufs.pojo.UsualMessageProtos;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ProtobufServer {
	private  HashMap<Byte,ProtobufsDecoder> decoders=new HashMap<Byte,ProtobufsDecoder>();
	{
		decoders.put((byte) 1,new ProtobufsDecoder(UsualMessageProtos.Login.getDefaultInstance()));
		decoders.put((byte) 2,new ProtobufsDecoder(UsualMessageProtos.Logout.getDefaultInstance()));
	}
	private  HashMap<Byte,MessageLite> encoders=new HashMap<Byte,MessageLite>();
	{
		encoders.put((byte) 1,UsualMessageProtos.Login.getDefaultInstance());
		encoders.put((byte) 2,UsualMessageProtos.Logout.getDefaultInstance());
	}
	public void start(int port)
	{
		NioEventLoopGroup boss=new NioEventLoopGroup();
		NioEventLoopGroup worker=new NioEventLoopGroup();
		ServerBootstrap sbt=new ServerBootstrap();
		sbt.group(boss, worker);
		sbt.channel(NioServerSocketChannel.class);
		sbt.option(ChannelOption.SO_BACKLOG, 65536);
		sbt.handler(new LoggingHandler(LogLevel.INFO));
		sbt.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				//解码器分配器
				sc.pipeline().addLast("ProtobufsDispatcherDecoder",new ProtobufsDispatcherDecoder(decoders));
				//指定编码器
				sc.pipeline().addLast("ProtobufsEncoder",new ProtobufsEncoder(encoders));
				//业务处理handler
				sc.pipeline().addLast(new ProtobufServerHandler());
			}
		});
		try {
			ChannelFuture cf=sbt.bind(port).sync();//等待绑定成功
			cf.channel().closeFuture().sync();//等待关闭
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	
	
	public static void main(String[] args) {
		new ProtobufServer().start(80);
	}
}
